import React, { useRef, useEffect } from 'react';
import { Paper } from '@mui/material';

/**
 * A reusable visual scroll debug logger component
 * Shows real-time scroll and element information without using state
 * to avoid unnecessary re-renders
 * 
 * @param {Object} props - Component props
 * @param {string} props.position - Position on screen ('top-right', 'top-left', 'bottom-right', 'bottom-left')
 * @param {string} props.title - Title for the logger panel
 * @param {boolean} props.showScrollY - Show current scroll Y position
 * @param {boolean} props.showWindowHeight - Show window height
 * @param {boolean} props.showViewportCenter - Show viewport center position
 * @param {boolean} props.showElementTop - Show observed element top position
 * @param {boolean} props.showElementCenter - Show observed element center position
 * @param {boolean} props.showDistanceFromCenter - Show distance from viewport center
 * @param {boolean} props.showNormalizedDistance - Show normalized distance (0=center, 1=edge)
 * @param {boolean} props.showScale - Show calculated scale value
 * @param {boolean} props.showPosition - Show position indicator (CENTER/MIDDLE/EDGE)
 * @param {boolean} props.showTime - Show current time
 * @param {Object} props.targetRef - React ref to the target element to observe
 * @param {number} props.maxScale - Maximum scale value at center (default: 1.5)
 * @param {number} props.minScale - Minimum scale value at edges (default: 1.0)
 * @param {Object} props.styling - Custom styling for the logger panel
 */
const VisualLogger = ({
  position = 'top-right',
  title = 'Scroll Debug Info',
  showScrollY = true,
  showWindowHeight = true,
  showViewportCenter = true,
  showElementTop = true,
  showElementCenter = true,
  showDistanceFromCenter = true,
  showNormalizedDistance = true,
  showScale = true,
  showPosition = true,
  showTime = true,
  targetRef = null,
  maxScale = 1.5,
  minScale = 1.0,
  styling = {}
}) => {
  const logRef = useRef(null);
  
  // Set positions based on prop
  const positionStyles = {
    'top-left': { top: 10, left: 10 },
    'top-right': { top: 10, right: 10 },
    'bottom-left': { bottom: 10, left: 10 },
    'bottom-right': { bottom: 10, right: 10 }
  };
  
  // Default styling merged with custom styling
  const defaultStyling = {
    position: 'fixed',
    zIndex: 9999,
    padding: 2,
    width: 280,
    opacity: 0.9,
    fontSize: '0.8rem',
    maxHeight: '80vh',
    overflow: 'auto',
    backgroundColor: 'white',
    ...positionStyles[position],
    ...styling
  };
  
  useEffect(() => {
    const handleScroll = () => {
      if (!logRef.current) return;
      
      // Get scroll and window data
      const scrollY = window.scrollY;
      const windowHeight = window.innerHeight;
      const viewportCenter = windowHeight / 2;
      
      // Default values for element-specific properties if no target ref provided
      let elementTop = 'N/A';
      let elementCenter = 'N/A';
      let distanceFromCenter = 'N/A';
      let normalizedDistance = 'N/A';
      let scale = 'N/A';
      let positionIndicator = 'N/A';
      
      // Calculate element-specific values if we have a target
      if (targetRef && targetRef.current) {
        const rect = targetRef.current.getBoundingClientRect();
        elementTop = rect.top;
        elementCenter = rect.top + rect.height / 2;
        distanceFromCenter = Math.abs(elementCenter - viewportCenter);
        normalizedDistance = distanceFromCenter / viewportCenter;
        
        // Calculate scale
        scale = minScale + (maxScale - minScale) * (1 - normalizedDistance);
        
        // Determine position indicator
        positionIndicator = normalizedDistance < 0.3 ? 'CENTER' : 
                            normalizedDistance < 0.7 ? 'MIDDLE' : 'EDGE';
      }
      
      // Build HTML content
      let html = `<div style="font-weight: bold; margin-bottom: 8px;">${title}</div>`;
      
      // Add data lines based on props
      if (showScrollY) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>scrollY:</span> <span style="font-family: monospace;">${typeof scrollY === 'number' ? scrollY.toFixed(2) : scrollY}</span>
        </div>`;
      }
      
      if (showWindowHeight) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>windowHeight:</span> <span style="font-family: monospace;">${typeof windowHeight === 'number' ? windowHeight.toFixed(2) : windowHeight}</span>
        </div>`;
      }
      
      if (showViewportCenter) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>viewportCenter:</span> <span style="font-family: monospace;">${typeof viewportCenter === 'number' ? viewportCenter.toFixed(2) : viewportCenter}</span>
        </div>`;
      }
      
      if (showElementTop && targetRef) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>elementTop:</span> <span style="font-family: monospace;">${typeof elementTop === 'number' ? elementTop.toFixed(2) : elementTop}</span>
        </div>`;
      }
      
      if (showElementCenter && targetRef) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>elementCenter:</span> <span style="font-family: monospace;">${typeof elementCenter === 'number' ? elementCenter.toFixed(2) : elementCenter}</span>
        </div>`;
      }
      
      if (showDistanceFromCenter && targetRef) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>distanceFromCenter:</span> <span style="font-family: monospace;">${typeof distanceFromCenter === 'number' ? distanceFromCenter.toFixed(2) : distanceFromCenter}</span>
        </div>`;
      }
      
      if (showNormalizedDistance && targetRef) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>normalizedDistance:</span> <span style="font-family: monospace;">${typeof normalizedDistance === 'number' ? normalizedDistance.toFixed(2) : normalizedDistance}</span>
        </div>`;
      }
      
      if (showScale && targetRef) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>scale:</span> <span style="font-family: monospace; ${typeof normalizedDistance === 'number' && normalizedDistance < 0.5 ? 'color: green;' : 'color: inherit;'}">${typeof scale === 'number' ? scale.toFixed(2) : scale}</span>
        </div>`;
      }
      
      if (showPosition && targetRef) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>position:</span> <span style="font-family: monospace;">${
            typeof normalizedDistance === 'number' && normalizedDistance < 0.3 ? '<strong style="color: green;">CENTER</strong>' : 
            typeof normalizedDistance === 'number' && normalizedDistance < 0.7 ? 'MIDDLE' : 'EDGE'
          }</span>
        </div>`;
      }
      
      if (showTime) {
        html += `<div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
          <span>time:</span> <span style="font-family: monospace;">${new Date().toLocaleTimeString()}</span>
        </div>`;
      }
      
      // Update log content
      logRef.current.innerHTML = html;
    };
    
    // Initial update
    handleScroll();
    
    // Add scroll listener
    window.addEventListener('scroll', handleScroll, { passive: true });
    
    // Add resize listener to handle window size changes
    window.addEventListener('resize', handleScroll, { passive: true });
    
    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', handleScroll);
    };
  }, [
    targetRef, 
    title, 
    maxScale, 
    minScale, 
    showScrollY, 
    showWindowHeight, 
    showViewportCenter, 
    showElementTop, 
    showElementCenter, 
    showDistanceFromCenter, 
    showNormalizedDistance, 
    showScale,
    showPosition,
    showTime
  ]);

  return <Paper ref={logRef} elevation={3} sx={defaultStyling} />;
};

export default VisualLogger;

